package com.hengtiansoft.lfy.fragment;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.activity.FullScrenActivity;
import com.hengtiansoft.lfy.activity.LoginActivity;
import com.hengtiansoft.lfy.activity.LoginActivityV2;
import com.hengtiansoft.lfy.activity.NewsDetailActivity;
import com.hengtiansoft.lfy.adapter.HistoryTranslateAdapter;
import com.hengtiansoft.lfy.adapter.NewsAdapter;
import com.hengtiansoft.lfy.base.BaseFragment;
import com.hengtiansoft.lfy.chart.activity.VoiceDialogActivity;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.db.been.InterpretRecordDB;
import com.hengtiansoft.lfy.entity.CollectEntity;
import com.hengtiansoft.lfy.entity.NewsEntity;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.Kdxf_TTSPlayer;
import com.hengtiansoft.lfy.utils.SharedUtil;
import com.hengtiansoft.lfy.utils.Utils;
import com.hengtiansoft.lfy.widget.CDeleteDialog;
import com.hengtiansoft.lfy.widget.CProgressDialog;
import com.hengtiansoft.lfy.widget.LoadMoreListView;
import com.hengtiansoft.lfy.widget.MySwipeMenuListView;
import com.hengtiansoft.lfy.widget.MyToast;
import com.hengtiansoft.pulltorefresh.PullToRefreshBase;
import com.hengtiansoft.pulltorefresh.PullToRefreshListView;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.ztspeech.constant.ZTConstant;
import com.ztspeech.translator.ZTTranslator;
import com.ztspeech.translator.interf.ZTTranslatorListener;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 翻译fragment
 * daiye
 */
public class TranslationFragment extends BaseFragment{
    private static final int ACTIVITY_RESULT_COLLECT_BTN_LOGIN = 10;
    private static final int ACTIVITY_RESULT_COLLECT_ITEM_LOGIN = 11;
    //全局界面及参数
    private View mRootView;
    private RelativeLayout mActivityRootView;
    private TextView mTranslateTitleLeft = null;
    private TextView mTranslateTitleRight = null;
    private ImageView mTranslateExchangeIv = null;
    private IDialogListener mListener = null;

    //输入界面
    private LinearLayout mInputLl = null;

    //语音图标
    private LinearLayout mDialogLl = null;

    //新闻界面
    private LinearLayout mNewsLl = null;
    private ImageView mInputCloseIv = null;
    private ImageView mHistoryIv = null;
    private ImageView mDialogIv = null;
    private ImageView openIv=null;
    private EditText mInputEt = null;
    private ImageView mEnterIv = null;
    private LinearLayout mLiuKongLl = null;
    private SwipeRefreshLayout refresh_layout_news;
    private LoadMoreListView mNewsListView = null;
    private NewsAdapter mNewsAdapter = null;

    private int mListPageNow = 1;
    private int mListTotalPage = 1;
    private int mMoveStartY = 0;
    private int mMoveDurY = 0;
    private int mTitleLlHeight = -1;
    private boolean mIsTitleLlHided = false;

    //翻译界面
    private LinearLayout mTranslateLl = null;
    private LinearLayout mHistoryLl = null;
    private ImageView mHistoryCloseIv = null;
    private TextView mHistoryTextSrcTv = null;
    private ImageView mRecordIv = null;
    private TextView mHistoryTextTranslateTv = null;
    private ImageView mHistorySpeakerSrcIv = null;
    private ImageView mHistorySpeakerTranslateIv = null;
    private ImageView mCopyIv = null;
    private ImageView mCollectIv = null;
    private ImageView mShareIv = null;
    private ImageView mHistoryDeleteIv = null;
    //private SwipeRefreshLayout refresh_layout_history;
    private PullToRefreshListView mPullToRefreshListView;
    private ListView mHistoryListView = null;
    private HistoryTranslateAdapter mHistoryTranslateAdapter = null;
    private CDeleteDialog mCDeleteDialog = null;

    private String mSearchStr = null;
    private boolean bIsChineseToEnglish = true;
    private ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();;
    private String voiceFilename;
    private RuntimeExceptionDao<InterpretRecordDB, Integer> mInterpretRecordDao = null;
    private List<InterpretRecordDB> mInterpretRecordDBList = null;

    private int mHistorySelectPosition = -1;
    private int mCollectItemPosition = -1;
    private boolean bNeedMonitorInputMethod = true;

    private boolean mIsKeyBoardHiden = true;
    private InputMethodManager mInputMethodManager = null;

    private CProgressDialog mProgressDialog = null;
    private static final int TranslateReturn = 1111;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_translation, container, false);
        initView();
        return mRootView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInputMethodManager = (InputMethodManager) getActivity().getApplication().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    public void onPause() {
        super.onPause();
        Kdxf_TTSPlayer.getInstense().stopTTs();
    }

    @Override
    public void onStop() {
        super.onStop();
        Kdxf_TTSPlayer.getInstense().stop();
    }

    private boolean showEnter = true;
    private boolean hideEnter = true;
    private void initView() {
        mProgressDialog = new CProgressDialog(getContext(), R.style.NetProcessDialog);
        mProgressDialog.setMessage(getString(R.string.is_translating));
        mProgressDialog.setCancelable(true);

        mActivityRootView = (RelativeLayout) mRootView.findViewById(R.id.activityRoot);
        mActivityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                mActivityRootView.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = mActivityRootView.getRootView().getHeight() - rect.bottom;
                if (rootInvisibleHeight < 300) {
                    //隐藏回车图标
                    if( hideEnter ) {
//                        final LinearLayout.LayoutParams paa = (LinearLayout.LayoutParams) mInputLl.getLayoutParams();
//                        final ValueAnimator animator1 = ValueAnimator.ofFloat(Utils.dp2px(getResources(), 144.0f), Utils.dp2px(getResources(), 44.0f));
//                        animator1.setDuration(150);
//                        animator1.setInterpolator(new DecelerateInterpolator());
//                        animator1.start();
//                        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                            @Override
//                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
//                                Float number = (Float) valueAnimator.getAnimatedValue();
//                                paa.height = number.intValue();
//                                mInputLl.setLayoutParams(paa);
//                            }
//                        });
                        hideEnter = false;
                        showEnter = true;

                        //键盘隐藏
                        mIsKeyBoardHiden = true;

                        //判断是否输入过文字，没有文字就隐藏回车
                        if(mInputEt!=null&&mInputEt.getText().length()==0&&mInputEt.hasFocus()){
                            mInputCloseIv.performClick();
                            //mInputCloseIv.performClick();
                        }

                        //关闭滑动删除
                        closeItems();
                    }
                } else {
                    //显示回车图标
                    if( showEnter ) {
//                        final LinearLayout.LayoutParams paa = (LinearLayout.LayoutParams) mInputLl.getLayoutParams();
//                        final ValueAnimator animator1 = ValueAnimator.ofFloat(Utils.dp2px(getResources(), 44.0f), Utils.dp2px(getResources(), 144.0f));
//                        animator1.setDuration(150);
//                        animator1.setInterpolator(new DecelerateInterpolator());
//                        animator1.start();
//                        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                            @Override
//                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
//                                Float number = (Float) valueAnimator.getAnimatedValue();
//                                paa.height = number.intValue();
//                                mInputLl.setLayoutParams(paa);
//                            }
//                        });
                        showEnter = false;
                        hideEnter = true;

                        //键盘弹出
                        if( bNeedMonitorInputMethod ) {
                            mInputLl.setVisibility(View.VISIBLE);
                            mNewsLl.setVisibility(View.GONE);
                            mHistoryLl.setVisibility(View.VISIBLE);
                            mTranslateLl.setVisibility(View.GONE);
                            mDialogLl.setVisibility(View.GONE);

                            mEnterIv.setVisibility(View.VISIBLE);

                            //把历史按钮换成关闭按钮
                            mInputCloseIv.setVisibility(View.VISIBLE);
                            mHistoryIv.setVisibility(View.GONE);
                        }
                        bNeedMonitorInputMethod = true;
                        mIsKeyBoardHiden = false;

                        //关闭滑动删除
                        closeItems();
                    }
                }
            }
        });

        mInputLl = (LinearLayout) mRootView.findViewById(R.id.input_ll);
        mDialogLl = (LinearLayout) mRootView.findViewById(R.id.dialog_ll);

        mTranslateTitleLeft = (TextView) mRootView.findViewById(R.id.translate_title_left_tv);
        mTranslateTitleRight = (TextView) mRootView.findViewById(R.id.translate_title_right_tv);
        mTranslateExchangeIv = (ImageView) mRootView.findViewById(R.id.translate_exchange_iv);
        //交换翻译类型  中文到英文 / 英文到中文
        mTranslateTitleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( bIsChineseToEnglish == true ) {
                    bIsChineseToEnglish = false;
                    mTranslateTitleLeft.setText(getText(R.string.translate_en));
                    mTranslateTitleRight.setText(getText(R.string.translate_zh));
                }
                else{
                    bIsChineseToEnglish = true;
                    mTranslateTitleLeft.setText(getText(R.string.translate_zh));
                    mTranslateTitleRight.setText(getText(R.string.translate_en));
                }
                //关闭滑动删除
                closeItems();
            }
        });
        mTranslateTitleRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( bIsChineseToEnglish == true ) {
                    bIsChineseToEnglish = false;
                    mTranslateTitleLeft.setText(getText(R.string.translate_en));
                    mTranslateTitleRight.setText(getText(R.string.translate_zh));
                }
                else{
                    bIsChineseToEnglish = true;
                    mTranslateTitleLeft.setText(getText(R.string.translate_zh));
                    mTranslateTitleRight.setText(getText(R.string.translate_en));
                }
                //关闭滑动删除
                closeItems();
            }
        });
        mTranslateExchangeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( bIsChineseToEnglish == true ) {
                    bIsChineseToEnglish = false;
                    mTranslateTitleLeft.setText(getText(R.string.translate_en));
                    mTranslateTitleRight.setText(getText(R.string.translate_zh));
                }
                else{
                    bIsChineseToEnglish = true;
                    mTranslateTitleLeft.setText(getText(R.string.translate_zh));
                    mTranslateTitleRight.setText(getText(R.string.translate_en));
                }
                //关闭滑动删除
                closeItems();
            }
        });

        //新闻界面
        mNewsLl = (LinearLayout) mRootView.findViewById(R.id.news_ll);
        mInputCloseIv = (ImageView) mRootView.findViewById(R.id.translate_input_close_iv);
        mHistoryIv = (ImageView) mRootView.findViewById(R.id.translate_history_iv);
        mDialogIv = (ImageView) mRootView.findViewById(R.id.dialogue_iv);
        mInputEt = (EditText) mRootView.findViewById(R.id.translate_input_et);
        mEnterIv = (ImageView) mRootView.findViewById(R.id.input_confirm_iv);
        mLiuKongLl = (LinearLayout) mRootView.findViewById(R.id.liukong_ll);
        refresh_layout_news = (SwipeRefreshLayout) mRootView.findViewById(R.id.refresh_layout_news);
        mNewsListView = (LoadMoreListView) mRootView.findViewById(R.id.list_news);
        mNewsAdapter = new NewsAdapter(getActivity());
        mNewsListView.setAdapter(mNewsAdapter);

        //关闭文本输入按钮
        mInputCloseIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( !mInputEt.getText().toString().equals("")){
                    mInputEt.setText("");
                }else{
                    mInputEt.setText("");
                    mInputEt.clearFocus();
                    if( !mIsKeyBoardHiden ){
                        //bNeedMonitorInputMethod = false;
                        //强制隐藏键盘
                        mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }
                    //把关闭按钮换成历史按钮
                    mInputCloseIv.setVisibility(View.GONE);
                    mHistoryIv.setVisibility(View.GONE);

                    mNewsLl.setVisibility(View.GONE);
                    mInputLl.setVisibility(View.VISIBLE);
                    mHistoryLl.setVisibility(View.VISIBLE);
                    mTranslateLl.setVisibility(View.GONE);
                    mDialogLl.setVisibility(View.GONE);

                    mEnterIv.setVisibility(View.GONE);
                }
                //关闭滑动删除
                closeItems();
            }
        });
        //进入历史翻译按钮
        mHistoryIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mInputLl.setVisibility(View.VISIBLE);
                mNewsLl.setVisibility(View.GONE);
                mHistoryLl.setVisibility(View.VISIBLE);
                mTranslateLl.setVisibility(View.GONE);
                mDialogLl.setVisibility(View.GONE);
                //把历史按钮换成关闭按钮
                mInputCloseIv.setVisibility(View.VISIBLE);
                mHistoryIv.setVisibility(View.GONE);

                //关闭滑动删除
                closeItems();
            }
        });
        //进入对话按钮
        mDialogIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if( mListener != null  )
//                    mListener.onDialogBtnClick();
                if (!CommonUtils.isFastDoubleClick()) {
                    startActivityForResult(
                            new Intent(getActivity(), VoiceDialogActivity.class)
                                    .putExtra("transferType", bIsChineseToEnglish ? "chen" : "ench"),
                            TranslateReturn);
                }
                //关闭滑动删除
                closeItems();
            }
        });

        //输入文本框监控Action按钮
        mInputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
                if( !TextUtils.isEmpty(mSearchStr)){
                    mInputEt.clearFocus();
                    if( !mIsKeyBoardHiden ){
                        bNeedMonitorInputMethod = false;
                        //强制隐藏键盘
                        mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        //把关闭按钮换成历史按钮
                        mInputCloseIv.setVisibility(View.GONE);
                        mHistoryIv.setVisibility(View.GONE);
                    }
                    mInputLl.setVisibility(View.GONE);
                    mNewsLl.setVisibility(View.GONE);
                    mHistoryLl.setVisibility(View.VISIBLE);
                    mTranslateLl.setVisibility(View.VISIBLE);
                    mDialogLl.setVisibility(View.GONE);
                    voiceFilename = "";
                    translate();
                }
                //关闭滑动删除
                closeItems();
                return true;
            }
        });
        //输入确定按钮
        mEnterIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( !TextUtils.isEmpty(mSearchStr)){
                    mInputEt.clearFocus();
                    if( !mIsKeyBoardHiden ){
                        bNeedMonitorInputMethod = false;
                        //强制隐藏键盘
                        mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        //把关闭按钮换成历史按钮
                        mInputCloseIv.setVisibility(View.GONE);
                        mHistoryIv.setVisibility(View.GONE);
                    }
                    mInputLl.setVisibility(View.GONE);
                    mNewsLl.setVisibility(View.GONE);
                    mHistoryLl.setVisibility(View.VISIBLE);
                    mTranslateLl.setVisibility(View.VISIBLE);
                    mDialogLl.setVisibility(View.GONE);
                    voiceFilename = "";
                    translate();
                }
                //关闭滑动删除
                closeItems();
            }
        });
        //输入文本框监控文字变化
        mInputEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSearchStr = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        //新闻下拉刷新
        refresh_layout_news.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics()));
        //refresh_layout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
        refresh_layout_news.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mNewsAdapter.clearData();
                mListPageNow = 1;
                mListTotalPage = 1;
                getNews();
            }
        });
        //新闻列表滚动动画
        mNewsListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mMoveDurY = 0;
                        mMoveStartY = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if( mMoveStartY == 0 ){
                            mMoveStartY = (int) motionEvent.getY();
                        }
                        int _TempY = (int) motionEvent.getY();
                        mMoveDurY = _TempY - mMoveStartY ;   //负数向上移动，正数向下移动
                        if ( mMoveDurY < -Utils.dp2px(getResources(),100) && mIsTitleLlHided == false) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsTitleLlHided = true;
                            menuCollapse();
                        } else if ( mMoveDurY > Utils.dp2px(getResources(),80) && mIsTitleLlHided == true) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsTitleLlHided = false;
                            menuExpand();
                        }
                        break;
                }
                return false;
            }
        });

        //新闻点击事件
        mNewsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mNewsAdapter.getData().size() != 0 && mNewsAdapter.getData().size() > i) {
                    NewsEntity.DataEntity entity = mNewsAdapter.getData().get(i);
                    Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(NewsDetailActivity.EXTRA_NEWS, entity);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });
        //新闻下拉加载
        mNewsListView.setInterface(new LoadMoreListView.ILoadListener() {
            @Override
            public void onLoad() {
                if (mListTotalPage <= mListPageNow) {
                    mNewsListView.setNoCommentViewVision(true, getString(R.string.list_nodata_tips));
                } else if (mListTotalPage > mListPageNow) {
                    mListPageNow = mListPageNow + 1;
                    getNews();
                }
            }
        });




        //History界面
        mTranslateLl = (LinearLayout) mRootView.findViewById(R.id.translate_ll);
        mHistoryLl = (LinearLayout) mRootView.findViewById(R.id.history_ll);
        mHistoryCloseIv = (ImageView) mRootView.findViewById(R.id.history_close_iv);
        mHistoryTextSrcTv = (TextView) mRootView.findViewById(R.id.history_src_tv);
        mRecordIv = (ImageView) mRootView.findViewById(R.id.record_iv);
        mHistoryTextTranslateTv = (TextView) mRootView.findViewById(R.id.history_translate_tv);
        mHistorySpeakerSrcIv = (ImageView) mRootView.findViewById(R.id.speaker_src_iv);
        mHistorySpeakerTranslateIv = (ImageView) mRootView.findViewById(R.id.speaker_translate_iv);
        mCopyIv = (ImageView) mRootView.findViewById(R.id.history_copy_iv);
        mCollectIv = (ImageView) mRootView.findViewById(R.id.history_collect_iv);
        openIv= (ImageView) mRootView.findViewById(R.id.history_open_iv);
        mShareIv = (ImageView) mRootView.findViewById(R.id.history_share_iv);
        mHistoryDeleteIv = (ImageView) mRootView.findViewById(R.id.history_delete_iv);
        //refresh_layout_history = (SwipeRefreshLayout) mRootView.findViewById(R.id.refresh_layout_history);
        mPullToRefreshListView = (PullToRefreshListView) mRootView.findViewById(R.id.list_history_translate);
        mPullToRefreshListView.setPullLoadEnabled(true);
        mPullToRefreshListView.setScrollLoadEnabled(false);
        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh( PullToRefreshBase<ListView> refreshView) {
//                mHistoryTextSrcTv.setText("");
//                mHistoryTextTranslateTv.setText("");
//                mCollectIv.setImageResource(R.drawable.btn_collection);
//                mHistorySelectPosition = -1;
                listItem.clear();
                getTranslateHistory(0);
                mPullToRefreshListView.onPullDownRefreshComplete(); //加载完成
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mPullToRefreshListView.onPullUpRefreshComplete(); //加载完成
            }
        });

        mHistoryListView = mPullToRefreshListView.getRefreshableView();
        mHistoryTranslateAdapter = new HistoryTranslateAdapter(getActivity());
        mHistoryListView.setAdapter(mHistoryTranslateAdapter);

        //翻译对话图标事件
        mRecordIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonUtils.isFastDoubleClick()) {
                    startActivityForResult(
                            new Intent(getActivity(), VoiceDialogActivity.class)
                                    .putExtra("transferType", bIsChineseToEnglish ? "chen" : "ench"),
                            TranslateReturn);
                }
                //关闭滑动删除
                closeItems();
            }
        });
        //翻译原文点击事件
        mHistoryTextSrcTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出键盘
                mInputEt.setText(mHistoryTextSrcTv.getText().toString());
                mInputEt.setSelection(mHistoryTextSrcTv.getText().toString().length());//将光标移至文字末尾
                mInputEt.setFocusable(true);
                mInputEt.setFocusableInTouchMode(true);
                mInputEt.requestFocus();
                //强制键盘弹出
                mInputMethodManager.showSoftInput(mInputEt,0);

                mInputLl.setVisibility(View.VISIBLE);
                mNewsLl.setVisibility(View.GONE);
                mHistoryLl.setVisibility(View.VISIBLE);
                mTranslateLl.setVisibility(View.GONE);
                mDialogLl.setVisibility(View.GONE);
                //把历史按钮换成关闭按钮
                mInputCloseIv.setVisibility(View.VISIBLE);
                mHistoryIv.setVisibility(View.GONE);

                //关闭滑动删除
                closeItems();
            }
        });
        //历史翻译记录每个条目上收藏按钮
        mHistoryTranslateAdapter.setOnClickListener(new HistoryTranslateAdapter.OnClickListener() {
            @Override
            public void onCollectClick(BaseAdapter adapter, View view, int position) {
                if( !Config.isUserLogined()){
                    MyToast.show(getActivity(),getString(R.string.not_logined_tips));
                    Intent intent = new Intent(getActivity(), LoginActivityV2.class);
                    startActivityForResult(intent, ACTIVITY_RESULT_COLLECT_ITEM_LOGIN);
                    return ;
                }else{
                    mCollectItemPosition = position;
                    collect(position);
                }
                //关闭滑动删除
                closeItems();
            }

            @Override
            public void onDeleteClick(BaseAdapter adapter, int position) {
                //从UI删除
                listItem.remove(position);
                mHistoryTranslateAdapter.notifyDataSetChanged();
                //从数据库删除
                if (null != mInterpretRecordDao) {
                    try {
                        @SuppressWarnings("rawtypes") //ormlite框架 删除数据
                                QueryBuilder builder = mInterpretRecordDao.queryBuilder();
                        builder.where().eq("username", "robot");
                        List<InterpretRecordDB>  interpretRecordDBList = builder.query();
                        deleteDataForInterpretRecordDBByid(interpretRecordDBList.get(interpretRecordDBList.size()-1-position).getId());
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                //关闭滑动删除
                closeItems();
            }
        });

        //原文喇叭播放
        mHistorySpeakerSrcIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( mHistorySelectPosition != -1 && mHistorySelectPosition < listItem.size() ){
                    HashMap<String, Object> item = listItem.get(mHistorySelectPosition);
                    String voicepath = item.get("voicefilename").toString();
                    if( !TextUtils.isEmpty(voicepath)){
                        Kdxf_TTSPlayer.getInstense().TTSPlayOpu(voicepath, mHistoryTextSrcTv.getText().toString());
                    }else{
                        //检查网络
                        if (Utils.isNetworkConnected(getActivity())) {
                            String synText = mHistoryTextSrcTv.getText().toString();
                            if (synText.length() <= 0)
                                return;
                            // if (!bIsChineseToEnglish)
                            Kdxf_TTSPlayer.getInstense().TTSPlay(synText, "", "");
                            //  else
                            //  Kdxf_TTSPlayer.getInstense().TTSPlay(synText, "ench", "");
                        } else {
                            Toast.makeText(getActivity(), getString(R.string.network_unknown_error),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                }
                //关闭滑动删除
                closeItems();
            }
        });
        //翻译喇叭播放
        mHistorySpeakerTranslateIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //检查网络
                if (Utils.isNetworkConnected(getActivity())) {
                    String synText = mHistoryTextTranslateTv.getText().toString();
                    if (synText.length() <= 0)
                        return;
                   // if (bIsChineseToEnglish)
                        Kdxf_TTSPlayer.getInstense().TTSPlay(synText, "", "");
                   // else
                      //  Kdxf_TTSPlayer.getInstense().TTSPlay(synText, "chen", "");
                } else {
                    Toast.makeText(getActivity(), getString(R.string.network_unknown_error),
                            Toast.LENGTH_LONG).show();
                }
                //关闭滑动删除
                closeItems();
            }
        });
        //复制按钮
        mCopyIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipboardManager cmb = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(mHistoryTextTranslateTv.getText().toString());
                MyToast.show(getActivity(),getString(R.string.translate_copy_tips));
                //关闭滑动删除
                closeItems();
            }
        });

        //收藏按钮
        mCollectIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( !Config.isUserLogined()){
                    MyToast.show(getActivity(),getString(R.string.not_logined_tips));
                    Intent intent = new Intent(getActivity(), LoginActivityV2.class);
                    startActivityForResult(intent, ACTIVITY_RESULT_COLLECT_BTN_LOGIN);
                    return ;
                }else{
                    if( mHistorySelectPosition != -1 && mHistorySelectPosition < listItem.size() ) {
                        if( ((String)listItem.get(mHistorySelectPosition).get("text")).equals(mHistoryTextSrcTv.getText().toString()))
                            collect(mHistorySelectPosition);
                    }
                }
                //关闭滑动删除
                closeItems();
            }
        });
        //分享按钮
        mShareIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String share_body = mHistoryTextSrcTv.getText().toString() + "  "  + mHistoryTextTranslateTv.getText().toString();
                SharedUtil.shared( getActivity(), getResources().getString(R.string.app_name), share_body, Constants.SHARE_URL);
                //关闭滑动删除
                closeItems();
            }
        });
        //历史翻译记录删除按钮
        mHistoryDeleteIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if( listItem.size() == 0 ){
                    MyToast.show(getActivity(),getString(R.string.collect_nodata_tips));
                    return;
                }

                showDeleteDialog();

                //关闭滑动删除
                closeItems();
            }
        });
        openIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), FullScrenActivity.class)
                        .putExtra("translate", mHistoryTextTranslateTv.getText().toString()));
                //关闭滑动删除
                closeItems();
            }
        });
        //历史翻译记录页面关闭
        mHistoryCloseIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出键盘
                mInputEt.setText("");
                mInputEt.setFocusable(true);
                mInputEt.setFocusableInTouchMode(true);
                mInputEt.requestFocus();
                //强制键盘弹出
                mInputMethodManager.showSoftInput(mInputEt,0);

                mInputLl.setVisibility(View.VISIBLE);
                mNewsLl.setVisibility(View.GONE);
                mHistoryLl.setVisibility(View.VISIBLE);
                mTranslateLl.setVisibility(View.GONE);
                mDialogLl.setVisibility(View.GONE);
                //把历史按钮换成关闭按钮
                mInputCloseIv.setVisibility(View.VISIBLE);
                mHistoryIv.setVisibility(View.GONE);

                //关闭滑动删除
                closeItems();
            }
        });

//        //历史翻译记录刷新
//        refresh_layout_history.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics()));
//        //refresh_layout_history.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
//        refresh_layout_history.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
////                mHistoryTextSrcTv.setText("");
////                mHistoryTextTranslateTv.setText("");
////                mCollectIv.setImageResource(R.drawable.btn_collection);
////                mHistorySelectPosition = -1;
//                listItem.clear();
//                getTranslateHistory(0);
//                refresh_layout_history.setRefreshing(false);
//            }
//        });

        //每条历史记录点击
        mHistoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if( i < listItem.size() ){
                    mInputEt.setText("");
                    mInputEt.clearFocus();
                    if( !mIsKeyBoardHiden ){
                        bNeedMonitorInputMethod = false;
                        //强制隐藏键盘
                        mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        //把关闭按钮换成历史按钮
                        mInputCloseIv.setVisibility(View.GONE);
                        mHistoryIv.setVisibility(View.GONE);
                    }
                    mNewsLl.setVisibility(View.GONE);
                    mInputLl.setVisibility(View.GONE);
                    mHistoryLl.setVisibility(View.VISIBLE);
                    mTranslateLl.setVisibility(View.VISIBLE);
                    mDialogLl.setVisibility(View.GONE);

                    HashMap<String, Object> item = listItem.get(i);
                    mHistoryTextSrcTv.setText(item.get("text").toString());
                    mHistoryTextTranslateTv.setText(item.get("translation").toString());
                    if (item.get("collected").toString().equals("Y")) {
                        mCollectIv.setImageResource(R.drawable.btn_collection_selected);
                    } else {
                        mCollectIv.setImageResource(R.drawable.btn_collection);
                    }
                    mHistorySelectPosition = i;
                }
                //关闭滑动删除
                closeItems();
            }
        });

        mHistoryLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭滑动删除
                closeItems();
            }
        });
         mRootView.findViewById(R.id.history_content_rl).setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 //关闭滑动删除
                 closeItems();
             }
         });
        mRootView.findViewById(R.id.input_content_rl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭滑动删除
                closeItems();
            }
        });
        mHistoryTextTranslateTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭滑动删除
                closeItems();
            }
        });
        mRootView.findViewById(R.id.translate_src_rl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭滑动删除
                closeItems();
            }
        });
        mRootView.findViewById(R.id.translate_translate_rl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭滑动删除
                closeItems();
            }
        });
        //获取新闻
        getNews();
        //获取翻译历史
        listItem.clear();
        getTranslateHistory(0);
    }

    /**
     * @desc   关闭滑动删除
     * @author taoli
     * @time 2017/2/28 0028
     */
    public void closeItems(){
        //关闭侧滑
        if ( mHistoryTranslateAdapter != null ) {
            mHistoryTranslateAdapter.closeAllItems();
        }
    }

    //点击底部buttom栏时显示翻译主页
    public void setOnFirstVisible(){
        mInputEt.setText("");
        mInputEt.clearFocus();
        if( !mIsKeyBoardHiden ){
            bNeedMonitorInputMethod = false;
            //强制隐藏键盘
            mInputMethodManager.hideSoftInputFromWindow(mActivityRootView.getWindowToken(), 0);
        }
        //把关闭按钮换成历史按钮
        mInputCloseIv.setVisibility(View.GONE);
        mHistoryIv.setVisibility(View.GONE);

        mNewsLl.setVisibility(View.GONE);
        mInputLl.setVisibility(View.VISIBLE);
        mHistoryLl.setVisibility(View.VISIBLE);
        mTranslateLl.setVisibility(View.GONE);
        mDialogLl.setVisibility(View.GONE);

        //关闭滑动删除
        closeItems();
    }

    //执行收藏/反收藏
    private void collect(final int position){
        HashMap<String, Object> item = listItem.get(position);
        int mode = -1;
        if (item.get("collected").toString().equals("Y")) {
            mode = 1;//取消收藏
        }else{
            mode = 0;//添加收藏
        }
        final int mMode = mode;
        NetHelper.collect(getActivity(), mode, item.get("text").toString(), item.get("translation").toString(), String.valueOf(item.get("serverId")), new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                CollectEntity entity = (CollectEntity)rspData;
                if ( entity.getRetcode() == 0) {
                    if( mMode == 0 ){
                        //添加收藏成功
                        double data = (Double) entity.getData();
                        listItem.get(position).put("collected", "Y");
                        listItem.get(position).put("serverId", (int)data ); //服务器返回serverId
                        mHistoryTranslateAdapter.notifyDataSetChanged();
                        updateDataForInterpretRecordDB((int)listItem.get(position).get("id"), "Y", (int)data);
                        Toast.makeText(getActivity(), getString(R.string.collect_success), Toast.LENGTH_LONG).show();
                        if( mHistorySelectPosition == position){
                            mCollectIv.setImageResource(R.drawable.btn_collection_selected);
                        }
                    }else{
                        //取消收藏成功
                        listItem.get(position).put("serverId", -1);
                        listItem.get(position).put("collected", "N");
                        mHistoryTranslateAdapter.notifyDataSetChanged();
                        updateDataForInterpretRecordDB((int)listItem.get(position).get("id"), "N", -1);
                        Toast.makeText(getActivity(), getString(R.string.uncollect_success), Toast.LENGTH_SHORT).show();
                        if( mHistorySelectPosition == position){
                            mCollectIv.setImageResource(R.drawable.btn_collection);
                        }
                    }
                }else{
                    Toast.makeText(getActivity(), entity.getMessage(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            }
        }, CollectEntity.class);
    }

    //执行翻译
    private void translate(){
        if( !TextUtils.isEmpty(mSearchStr)){
            if ( mProgressDialog != null && !mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }
            if(bIsChineseToEnglish){
                ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_CHEN);
            }else{
                ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_ENCH);
            }
            ZTTranslator.getTranslatorInstance().translate(mTranLisenter,mSearchStr);
        }
        if (!TextUtils.isEmpty(mSearchStr)) {
            mInputLl.setVisibility(View.GONE);
            mNewsLl.setVisibility(View.GONE);
            mTranslateLl.setVisibility(View.VISIBLE);
            mHistoryLl.setVisibility(View.VISIBLE);
            mDialogLl.setVisibility(View.GONE);
        }
    }

    //执行历史记录清楚
    private void showDeleteDialog(){
        if ( mCDeleteDialog == null) {
            mCDeleteDialog = new CDeleteDialog(getActivity());
            mCDeleteDialog.setItemClickListener(new CDeleteDialog.OnItemClick() {
                @Override
                public void onItemClick(int position) {
                    if (position == 1) {
                        deleteDataForInterpretRecordDB();
                    }
                }
            });
            mCDeleteDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                }
            });
            Window window = mCDeleteDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.pop_float_win_anim_style);
        }
        mCDeleteDialog.show();
    }

    private void getTranslateHistory(int loadStartIndex){
        getDataForInterpretRecord(loadStartIndex);
    }

    private void getNews() {
        NetHelper.getNewsList(getActivity(), mListPageNow, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                mNewsListView.loadComplete();
                refresh_layout_news.setRefreshing(false);
                NewsEntity info = (NewsEntity) rspData;
                if (info.getRetcode() == 0) {
                    List<NewsEntity.DataEntity> mMeetingEntities = info.getData();
                    mListTotalPage = info.getTotalPage();
                    mNewsAdapter.addData(mMeetingEntities);
                    if ( mNewsAdapter.getData().size() != 0) {
                        mNewsListView.setVisibility(View.VISIBLE);
                    } else {
                        mNewsListView.setVisibility(View.GONE);
                    }
                } else {
                    Toast.makeText(getActivity(), info.getMessage(), Toast.LENGTH_SHORT).show();
                    mNewsListView.setVisibility(View.GONE);
                }
            }

            @Override
            public void failed(String msg) {
                mNewsListView.loadComplete();
                refresh_layout_news.setRefreshing(false);
                mNewsListView.setVisibility(View.GONE);
                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            }
        }, NewsEntity.class);
    }

    private void menuCollapse() {
        final LinearLayout.LayoutParams paa = (LinearLayout.LayoutParams) mLiuKongLl.getLayoutParams();
        if (mTitleLlHeight == -1)
            mTitleLlHeight = paa.height;
        final ValueAnimator animator1 = ValueAnimator.ofFloat(mTitleLlHeight, 0);
        animator1.setDuration(250);
        animator1.setInterpolator(new DecelerateInterpolator());
        animator1.start();
        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                Float number = (Float) valueAnimator.getAnimatedValue();
                paa.height = number.intValue();
                mLiuKongLl.setLayoutParams(paa);
            }
        });
    }

    private void menuExpand() {
        final LinearLayout.LayoutParams paa = (LinearLayout.LayoutParams) mLiuKongLl.getLayoutParams();
        final ValueAnimator animator1 = ValueAnimator.ofFloat(0, mTitleLlHeight);
        animator1.setDuration(250);
        animator1.setInterpolator(new DecelerateInterpolator());
        animator1.start();
        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                Float number = (Float) valueAnimator.getAnimatedValue();
                paa.height = number.intValue();
                mLiuKongLl.setLayoutParams(paa);
            }
        });
    }

    /**
     * 紫冬翻译回调接口
     */
    private ZTTranslatorListener mTranLisenter = new ZTTranslatorListener() {
        @Override
        public void onResult(String text) {
            if ( mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            setDataToInterpretRecord(mSearchStr, text, voiceFilename); //存储
        }

        @Override
        public void onError(int i) {
            if ( mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            Toast.makeText(getActivity(), getString(R.string.translate_error_tips), Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_COLLECT_BTN_LOGIN) {
            if (resultCode == Activity.RESULT_OK && Config.isUserLogined()) {
                if( mHistorySelectPosition != -1 && mHistorySelectPosition < listItem.size() )
                    collect(mHistorySelectPosition);
            }
        }
        if (requestCode == ACTIVITY_RESULT_COLLECT_ITEM_LOGIN) {
            if (resultCode == Activity.RESULT_OK && Config.isUserLogined()) {
                if( mCollectItemPosition != -1 && mCollectItemPosition < listItem.size() )
                    collect(mCollectItemPosition);
            }
        }
        if(requestCode==TranslateReturn) {
            if(data==null){
                return;
            }
            String res = data.getStringExtra("result");
            if (res != null && !res.equals("")) {
                if (res.equals(Constants.No_RESULT)) {
                    if(bIsChineseToEnglish==false){
                        Toast.makeText(getActivity(), getString(R.string.say_againe),
                                Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(getActivity(), getString(R.string.say_again),
                                Toast.LENGTH_SHORT).show();
                    }
                } else if (res.equals(Constants.ZR_ERROR)) {
                    Toast.makeText(getActivity(), getString(R.string.recognition_error), Toast.LENGTH_SHORT)
                            .show();
                } else if (res.equals(Constants.ZR_STOP_NULL)) {
                    return;
                } else {
                    voiceFilename = data.getStringExtra("url");//压缩过后的原始语音
                    mSearchStr=res;
                    if( !TextUtils.isEmpty(mSearchStr)){
                        mInputEt.clearFocus();
                        if( !mIsKeyBoardHiden ){
                            bNeedMonitorInputMethod = false;
                            //强制隐藏键盘
                            mInputMethodManager.hideSoftInputFromWindow(mEnterIv.getWindowToken(), 0);
                            //把关闭按钮换成历史按钮
                            mInputCloseIv.setVisibility(View.GONE);
                            mHistoryIv.setVisibility(View.GONE);
                        }
                        mInputLl.setVisibility(View.GONE);
                        mNewsLl.setVisibility(View.GONE);
                        mHistoryLl.setVisibility(View.VISIBLE);
                        mTranslateLl.setVisibility(View.VISIBLE);
                        mDialogLl.setVisibility(View.GONE);
                        translate();
                    }
                }
            } else {
                Toast.makeText(getActivity(), getString(R.string.recognition_error), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    /**
     * 本地数据库缓存
     */
    public void getDataForInterpretRecord(int startIndex) {
        String username = "robot";
        InterpretRecordDB interpretRecordDB = new InterpretRecordDB();
        interpretRecordDB.setUsername(username);
        mInterpretRecordDao = LFYApplication.getHelper(getActivity()).getInterpretRecordDao();
        //查询数据
        if (null != mInterpretRecordDao) {
            try {
                @SuppressWarnings("rawtypes")
                QueryBuilder builder = mInterpretRecordDao.queryBuilder();
                builder.where().eq("username", username);
                mInterpretRecordDBList = builder.query();
            } catch (SQLException e) {
                mInterpretRecordDBList = null;
                return;
            }
        }

        /*
        //使用分页加载
        int maxCount = mInterpretRecordDBList.size();
        int pageSize = 10;
        int endIndex = startIndex + pageSize;
        if ( endIndex > maxCount ) {
            pageSize = pageSize - (endIndex - maxCount);
        }
        if( pageSize < 10 ) {
            mHistoryListView.setNoCommentViewVision(true, getString(R.string.collect_nodata_tips));
        }

        if (null != mInterpretRecordDBList
                && mInterpretRecordDBList.size() > 0) {
            for (int i = startIndex; i < startIndex + pageSize; i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("text", mInterpretRecordDBList.get(i).getText());
                map.put("translation",
                        mInterpretRecordDBList.get(i).getTranslation());
                map.put("id", mInterpretRecordDBList.get(i).getId());
                map.put("collected",
                        mInterpretRecordDBList.get(i).getIscollected());
                map.put("voicefilename",
                        mInterpretRecordDBList.get(i).getFilename());
                map.put("serverId",
                        mInterpretRecordDBList.get(i).getServerId());
                listItem.add(map);
            }
        }*/

        //数据从堆栈底从下往上取，数据库里最下面的显示在列表框最上面
        if (null != mInterpretRecordDBList
                && mInterpretRecordDBList.size() > 0) {
            for (int i = mInterpretRecordDBList.size() -1 ; i >= 0; i--) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("text", mInterpretRecordDBList.get(i).getText());
                map.put("translation",
                        mInterpretRecordDBList.get(i).getTranslation());
                map.put("id", mInterpretRecordDBList.get(i).getId());
                map.put("collected",
                        mInterpretRecordDBList.get(i).getIscollected());
                map.put("voicefilename",
                        mInterpretRecordDBList.get(i).getFilename());
                map.put("serverId",
                        mInterpretRecordDBList.get(i).getServerId());
                listItem.add(map);
            }
        }
        mHistoryTranslateAdapter.setData(listItem);

        //默认滚动到最上
        if( listItem.size() != 0 )
            mHistoryListView.setSelection(0);
    }

    /**
     * 本地数据库缓存
     */
    public void setDataToInterpretRecord(String text, String translation,
                                         String voiceFilename) {
        String username = "robot";
        InterpretRecordDB interpretRecordDB = new InterpretRecordDB();
        interpretRecordDB.setUsername(username);
        interpretRecordDB.setText(text);
        interpretRecordDB.setTranslation(translation);
        interpretRecordDB.setIscollected("N");
        interpretRecordDB.setFilename(voiceFilename);
        interpretRecordDB.setServerId(-1);
        mInterpretRecordDao = LFYApplication.getHelper(getActivity())
                .getInterpretRecordDao();
        if (null != mInterpretRecordDao) {
            mInterpretRecordDao.create(interpretRecordDB);
            try {
                @SuppressWarnings("rawtypes") //ormlite框架 删除数据
                        QueryBuilder builder = mInterpretRecordDao.queryBuilder();
                builder.where().eq("username", username);
                mInterpretRecordDBList = builder.query();
            } catch (SQLException e) {
                mInterpretRecordDBList = null;
            }
        }
        //取数据库最后一条数据显示
        if (null != mInterpretRecordDBList
                && mInterpretRecordDBList.size() > 0) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("text", mInterpretRecordDBList
                    .get(mInterpretRecordDBList.size() - 1).getText());
            map.put("translation", mInterpretRecordDBList
                    .get(mInterpretRecordDBList.size() - 1).getTranslation());
            map.put("id", mInterpretRecordDBList
                    .get(mInterpretRecordDBList.size() - 1).getId());
            map.put("collected", mInterpretRecordDBList
                    .get(mInterpretRecordDBList.size() - 1).getIscollected());
            map.put("voicefilename", mInterpretRecordDBList
                    .get(mInterpretRecordDBList.size() - 1).getFilename());
            map.put("serverId", mInterpretRecordDBList
                    .get(mInterpretRecordDBList.size() - 1).getServerId());

            //最新的数据最上面显示
            ArrayList<HashMap<String, Object>> listItemTemp = new ArrayList<HashMap<String, Object>>();
            listItemTemp.add(map);
            listItemTemp.addAll(listItem);
            listItem.clear();
            listItem.addAll(listItemTemp);

            mHistoryTranslateAdapter.setData(listItem);
            //mHistoryListView.setSelection(ListView.FOCUS_DOWN);
            mHistoryTextSrcTv.setText(text);
            mHistoryTextTranslateTv.setText(translation);
            mHistorySelectPosition = 0;  //每次插入数据的时候默认选中第一条（最新数据）
            mCollectIv.setImageResource(R.drawable.btn_collection);   //取消之前有可能的收藏选中状态
            mInputLl.setVisibility(View.GONE);
            mNewsLl.setVisibility(View.GONE);
            mHistoryLl.setVisibility(View.VISIBLE);
            mTranslateLl.setVisibility(View.VISIBLE);
            mDialogLl.setVisibility(View.GONE);
            mInputEt.setText("");
        }
    }

    /**
     * 修改收藏状态
     */
    public void updateDataForInterpretRecordDB(int id, String iscollected,
                                               int serverId) {
        InterpretRecordDB interpretRecordDB1 = new InterpretRecordDB();
        interpretRecordDB1.setId(id);
        mInterpretRecordDao = LFYApplication.getHelper(getActivity())
                .getInterpretRecordDao();
        if (null != mInterpretRecordDao) {
            try {
                @SuppressWarnings("rawtypes")
                QueryBuilder builder = mInterpretRecordDao.queryBuilder();
                builder.where().eq("id", id);
                mInterpretRecordDBList = builder.query();
            } catch (SQLException e) {
                mInterpretRecordDBList = null;
            }
        }
        if (null != mInterpretRecordDBList
                && mInterpretRecordDBList.size() > 0) {
            InterpretRecordDB interpretRecordDB = new InterpretRecordDB();
            interpretRecordDB.setId(id);
            interpretRecordDB.setIscollected(iscollected);
            interpretRecordDB.setText(mInterpretRecordDBList.get(0).getText());
            interpretRecordDB.setTranslation(
                    mInterpretRecordDBList.get(0).getTranslation());
            interpretRecordDB
                    .setUsername(mInterpretRecordDBList.get(0).getUsername());
            interpretRecordDB
                    .setFilename(mInterpretRecordDBList.get(0).getFilename());
            interpretRecordDB.setServerId(serverId);
            LFYApplication.getHelper(getActivity()).getInterpretRecordDao()
                    .update(interpretRecordDB);
        }
    }

    /**
     * 删除本地数据库
     */
    public void deleteDataForInterpretRecordDB() {
        String username = "robot";
        try {
            DeleteBuilder<InterpretRecordDB, Integer> deleteBuilder = mInterpretRecordDao
                    .deleteBuilder();
            deleteBuilder.where().eq("username", username);
            deleteBuilder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        mHistoryTranslateAdapter.clearData();
    }

    /**
     * 本地数据库
     */
    public void deleteDataForInterpretRecordDBByid(int id) {
        try {
            // 删除指定的信息，类似delete User where 'id' = id ;
            DeleteBuilder<InterpretRecordDB, Integer> deleteBuilder = mInterpretRecordDao
                    .deleteBuilder();
            deleteBuilder.where().eq("id", id);
            deleteBuilder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void setDialogClickListener( IDialogListener l ){
        mListener = l;
    }

    public interface  IDialogListener{
        public void onDialogBtnClick();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            listItem.clear();
            getTranslateHistory(0);
            mHistoryTranslateAdapter.notifyDataSetChanged();
        }
    }


}
